package mall.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import mall.bean.User;
import mall.service.UserService;
import mall.service.impl.UserServiceImpl;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserService userService = new UserServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 防止一会获取参数时乱码
		req.setCharacterEncoding("UTF-8");
		// 获取参数
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		// 调用业务方法进行注册, 得到结果
		User user = new User();
		user.setUserName(username);
		user.setPassword(password);
		Result result;
		try {
			this.userService.register(user);
			result = Result.success("注册成功");
		} catch (Exception e) {
			result = Result.error("注册失败");
		}
		// 准备好响应内容
		String jsonResult = JSON.toJSONString(result, true);
		// 返回响应内容给前端
		resp.setContentType("application/json;charset=UTF-8");
		PrintWriter writer = resp.getWriter();
		writer.append(jsonResult);
	}
	
}





